package com.immomo.test;

import com.immomo.test.common.FileUtil;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.tinify.Source;
import com.tinify.Tinify;
import org.apache.log4j.Level;

import java.io.File;

public class TinyPNG extends AnAction {

    private Project mProject;
    private static final Logger log = Logger.getInstance("TinyPNG");
    static {
        log.setLevel(Level.INFO);
    }
    @Override
    public void actionPerformed(AnActionEvent event) {
        mProject = event.getData(PlatformDataKeys.PROJECT);
        DataContext dataContext = event.getDataContext();
        if ("jpg".equals(getFileExtension(dataContext)) || "png".equals(getFileExtension(dataContext)) ) {//根据扩展名判定是否进行下面的处理
            //获取选中的文件
            VirtualFile file = DataKeys.VIRTUAL_FILE.getData(event.getDataContext());
            if (file != null) {
                doCompressImage(file.getPath());
            } else {
                Messages.showErrorDialog(mProject, "文件异常", "压缩失败");
            }
        } else {
            Messages.showErrorDialog(mProject, "只支持图片文件压缩", "压缩失败");
        }
    }

//    @Override
//    public void update(AnActionEvent event) {
//        //在Action显示之前,根据选中文件扩展名判定是否显示此Action
//        String extension = getFileExtension(event.getDataContext());
//        this.getTemplatePresentation().setEnabled("png".equals(extension) || "jpg".equals(extension));
//    }

    public static String getFileExtension(DataContext dataContext) {
        VirtualFile file = DataKeys.VIRTUAL_FILE.getData(dataContext);
        return file == null ? null : file.getExtension();
    }

    public void doCompressImage(String originPath) {
        int message = Messages.showOkCancelDialog(mProject, "开始压缩：" + originPath, "提示", Messages.getInformationIcon());
        if (message != 0) {
            return;
        }

        String key = FileUtil.loadAPiKey();
        boolean userCustom = true;
        if (key == null || "".equals(key.trim())) {
            userCustom = false;
            key = "xxx";//
        }

        Tinify.setKey(key);
        log.info("start compress image: " + originPath);
        String tempFilePath = originPath + "_tmp";
        File oriFile = new File(originPath);
        File desFile = new File(tempFilePath);
        if (!oriFile.exists()) {
            Messages.showErrorDialog(mProject, "文件不存在: " + originPath, "压缩失败");
            return;
        }
        boolean finalUserCustom = userCustom;
        ProgressManager.getInstance().runProcessWithProgressSynchronously(
                new Runnable() {
                    @Override
                    public void run() {
                        ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
                        progressIndicator.setIndeterminate(true);
                        try {
                            Source source = Tinify.fromFile(originPath);
                            source.toFile(tempFilePath);

                            float fileSize = FileUtil.getFileSize(oriFile);
                            float destFileSize = FileUtil.getFileSize(desFile);
                            FileChangeDetectApplicationComponent.compressedPaths.add(originPath);
                            FileChangeDetectApplicationComponent.compressedTime = System.currentTimeMillis();
                            FileUtil.renameTo(desFile, oriFile);
                            log.info("压缩成功：oriFle size: " + fileSize + ", destFileSize = " + destFileSize + " , 减少 = " + (int)((fileSize - destFileSize)/fileSize * 100) + "%");
                            showSuccessMessage(String.format("源文件大小：%.2fKB \n压缩后大小：%.2fKB \n压缩比：%.2f %% \n %s", fileSize, destFileSize, (fileSize - destFileSize)/fileSize * 100, finalUserCustom ? "自定义API KEY" : "默认API Key"));
                        } catch (Exception e) {
                            log.trace(e);
                            showErrorMessage("压缩失败：" + e.getMessage());
                        }
                    }
                }, "正在处理", true, null
        );

    }

    private void showSuccessMessage(String message) {
        ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
                Messages.showMessageDialog(message, "压缩成功", Messages.getInformationIcon());
            }
        });
    }


    private void showErrorMessage(String message) {
        ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
                Messages.showErrorDialog(mProject, "" + message, "压缩失败");
            }
        });
    }
}
